package com.leha.api.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

public class RequestLoggerFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestLoggerFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = ((HttpServletRequest) request);
            String path = httpRequest.getServletPath();
            LOG.info("请求路径:" + path);
            LOG.info("请求方法:" + httpRequest.getMethod());
            Enumeration<String> names = request.getParameterNames();
            LOG.info("请求" + httpRequest.getRequestURI());
            LOG.info("请求参数:");
            while (names.hasMoreElements()) {
                String key = names.nextElement();
                LOG.info(key + ":" + request.getParameter(key));
            }
        } catch (Exception e) {
            LOG.info("解析请求出错");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
